package a07_二叉树;

/**
 * <p>
 * a19_最大二叉树复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/4/14
 */
public class a19_最大二叉树复习3 {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        if (nums.length == 0) {
            return null;
        }
        int rootVal = Integer.MIN_VALUE;
        int rootIdx = -1;
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] > rootVal){
                rootVal = nums[i];
                rootIdx = i;
            }
        }

        TreeNode rootNode = new TreeNode(rootVal);
        rootNode.left = constructMaximumBinaryTree(split(nums, 0, rootIdx - 1));
        rootNode.right = constructMaximumBinaryTree(split(nums, rootIdx + 1, nums.length - 1));
        return rootNode;
    }

    private int[] split(int[] nums,int leftIdx,int rightIdx){
        int[] result = new int[rightIdx  - leftIdx + 1];
        int newIdx = 0;
        while (leftIdx <= rightIdx){
            result[newIdx] = nums[leftIdx];
            leftIdx++;
            newIdx++;
        }
        return result;
    }
}
